package com.example.springboot.mockData;

import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.Random;

public class GenerateBatchData {
    private String sql="INSERT INTO workshop (name,state,equipment_num,manager,phone) VALUES (?,?,?,?,?)";
    private String charset="utf-8";
    private String connectStr="jdbc:mysql://10.219.64.135:3306/test";
    private String username="root";
    private String password="123456";
    private void doStore() throws ClassNotFoundException, SQLException, IOException {
        Class.forName("com.mysql.jdbc.Driver");
        connectStr += "?useServerPrepStmts=false&rewriteBatchedStatements=true";//此处是测试高效批次插入，去掉之后执行时普通批次插入
        Connection conn = (Connection) DriverManager.getConnection(connectStr, username,password);
        conn.setAutoCommit(false); // 设置手动提交
        int count = 0;
        PreparedStatement psts = conn.prepareStatement(sql);
        String line = null;
        Date begin=new Date();
        for(int i=0;i<500;i++){
            psts.setString(1, "ws" + new Random().nextInt(500));
            psts.setString(2, new Random().nextInt(2) == 1 ? "正在运行" : "待机");
            psts.setInt(3, new Random().nextInt(10));
            psts.setString(4, "admin");
            psts.setString(5, "phone" + new Random().nextInt(10000));
            psts.addBatch();          // 加入批量处理
            count++;
        }
        psts.executeBatch(); // 执行批量处理
        conn.commit();  // 提交
        Date end=new Date();
        System.out.println("数量="+count);
        System.out.println("运行时间="+(end.getTime()-begin.getTime()));
        conn.close();
    }
    public static void main(String[] args) {
        try {
            new GenerateBatchData().doStore();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}